layui.use('laydate', function(){
	  var laydate = layui.laydate;
	  
	  lay('.test-item').each(function(){
		    laydate.render({
		      elem: this
		      ,trigger: 'click'
		    });
		  });
});	 
/**
 * 从地址栏传值的代码
 * @param param
 * @returns
 */
function getParameter(param){
	var query = window.location.search;
	var iLen = param.length;
	var iStart = query.indexOf(param);
	if (iStart == -1)
		return "";
	iStart += iLen + 1;
	var iEnd = query.indexOf("&", iStart);
	if (iEnd == -1)
		return query.substring(iStart);
	return query.substring(iStart, iEnd);
}
//刷新页面是给文本框赋值为0
$('#inputss').val("");
$("#inputText").val("");
var value;
layui.use('table', function(){
  var table = layui.table;
  /*//监听单元格编辑
  table.on('edit(demos)', function(obj){
	  alert(1);
     value = obj.value //得到修改后的值
    ,data = obj.data //得到所在行所有键值
    ,field = obj.field; //得到字段
    layer.msg(value);
    alert(2)
   
  });*/
//监听工具条
  table.on('tool(demos)', function(obj){
    var da = obj.data;
    //删除
    if(obj.event === 'del'){
      layer.confirm('真的删除行么', function(index){
    	obj.del();
    	layer.close(index);
        var url="../../listenPurchaseDetail/delete.action";
        var data={"isva":2,"pdId":da.pdId};
        $.post(url,data,function(mes){
        	if(mes>0){
        		layer.msg("删除成功");
        	     removeChecked(da.vocationalWorkId);
        	}
        },"json");
       
      });
    } 
  });
//执行一个 table 实例
  table.render({
	     elem: '#goods'
	    ,url: '../../listenPurchaseDetail/findAll.action?purchaseId='+getParameter("id") //数据接口
	    ,page: true //开启分页
	    ,method:'post'
	    ,cols: [[ //表头
	       {field: 'pdId', title: '采购明细ID', width:120, fixed: 'left'}
	      ,{field: 'purchaseId', title: '采购订单号', width:260}
	      ,{field: 'pdName', title: '物品', width: 182}
	      ,{field: 'pdNumber', title: '物品数量', width:140,toolbar:'#purNumber',sort:"true"}
	      ,{field: 'pdPrice', title: '进价', width: 140}
	      ,{field: 'pdSubtotal', title: '小计',toolbar:'#pdSubtotal', width: 140}
	      ,{field: 'vocationalWorkId', title: '业务id',width: 120}
	      ,{fixed: 'right',title: '操作', width: 180, align:'center', toolbar: '#barDemo'}
	    ]]
	  	,id: 'testReload'
		,done: function (res, curr, count) {
	        $("[data-field='pdId']").css('display','none');
	        $("[data-field='vocationalWorkId']").css('display','none');
	        $("[data-field='purchaseId']").css('display','none');
	    }
	  });
//监听表格复选框选择
 
  /*var myArray=new Array();*/
  var table2=document.getElementById("idTest3");
  table.on('checkbox(demo)', function(obj){
	  var tr2=document.createElement("tbody");
	  var da = obj.data;
	//判断是否全选
    if(obj.type=="all"){
    	 //获取表格所有的
    	 var tableAll=table.cache.idTest;
    	 		
	 		if(obj.checked==true){
	 				$(".trsId").remove();
	 				for (var i = 0; i < tableAll.length; i++) {
	    	       		tr2.innerHTML+= "<tr id="+tableAll[i].muId+" class='trsId'><td style='display: none'>"+tableAll[i].muId+"</td><td id='muName'>"+tableAll[i].muName+"</td><td>"+tableAll[i].wholesale+"</td><td><input type=text maxlength='5' class='inputs-number' name='nubText' value='0' onInput ='keypress(this)' onkeyup='upperCase(this)'/></td><td><input type=text value='0' readonly  class='inputskx' /></td><td style='display:none;' >"+tableAll[i].stockNumber+"<td><a class='layui-btn layui-btn-danger layui-btn-xs' href='javascript:exit(\""+tableAll[i].muId+"\");'>删除</a></td></tr>";
	    	       		table2.appendChild(tr2);//添加tr节点
	 				}
	 		}else{
	 			$(".trsId").remove();
	 			$('#inputss').val("");
	 		}
    	 		
    	    		
    	
    //判断单选	
    }else if(obj.type=="one"){
    	/*var checkStatus = table.checkStatus('idTest')
	      ,data = checkStatus.data;
	      layer.alert(JSON.stringify(data));
	      var tableAll=table.cache.idTest;
	      var datas=JSON.stringify(data);*/
    	var inputVal=$('#inputss').val();
    	if(obj.checked==true){
    		tr2.innerHTML+= "<tr id="+da.muId+" class='trsId'><td style='display: none'>"+da.muId+"</td><td>"+da.muName+"</td><td>"+da.wholesale+"</td><td><input type=text maxlength='5' class='inputs-number' value='0' name='nubText'  onInput ='keypress(this)' onkeyup='upperCase(this)'/></td><td><input type=text value='0' readonly  class='inputskx' /></td><td  style='display:none;'>"+da.stockNumber+"</td><td><a class='layui-btn layui-btn-danger layui-btn-xs' href='javascript:exit(\""+da.muId+"\");'>删除</a></td></tr>";
        	
        	table2.appendChild(tr2);//添加tr节点

        	
				
    	}else{
    		
    		$("#"+da.muId+"").remove();
    	}
    	
    	
        	
	  }
  });
  
 
  //表单重载
  var $ = layui.$, active = {
		    reload: function(){
		    	var demoReload = $('#demoReload');
		    	var startPrice = $('#startPrice');
		    	var EndPrice = $('#EndPrice');
		    	var type = $('#mtType');
		      //执行重载
		      table.reload('idTest', {
		        page: {
		          curr: 1 //重新从第 1 页开始
		        }
		        ,where: { 
		        	muName:demoReload.val(),
		        	startPrice:startPrice.val(),
		        	EndPrice:EndPrice.val(),
		        	mtId:type.val(),
		        }
		      });
		    }
		  };
  
  
  
  $('.demoTable .layui-btn').on('click', function(){
    var type = $(this).data('type');
    active[type] ? active[type].call(this) : '';
  });
 
 
//类型显示
	var url="../../listenMusicalType/mutype.action"
	var data=null;
	$.post(url,data,function(mes){
		$.each(mes,function(index,item){
				$("#mtType").append("<option value='"+item.mtId+"'>"+item.mtName+"</option>");
				load();
		});
	},"json");
	
  //点击添加
  $("#insertPurchase").click(function(){
	     var sum = 0 ;
		$("input[name='title']").each(function(){
			  if( $(this).val().trim() != '' ) { 
				sum+=parseInt($(this).val());
			  }
			});
		
		var sumPrvice=0;
		$("input[name='titles']").each(function(){
			 if( $(this).val().trim() != '' ) { 
			  sumPrvice+=parseInt($(this).val());
			 }
		});
		
	  $("#inputss").val("");
	  $("#inputText").val("");
	  //var sumPrice=0;
	 /* //循环获取小计的值
	  $(".inputskx").each(function(){
		 sumPrice+=parseFloat($(this).val());
	  })
	  var sumNum=0;
	  //循环获取数量的值
	  $(".inputs-number").each(function(){
		  sumNum+=parseFloat($(this).val());
	  })*/
	  $("#inputText").val(sumPrvice+","+sum);
	  GetInfoFromTable("idTest3");
  })
  
});
function exit(obj){
	$("#"+obj+"").remove();
	removeChecked(obj);
}
/**
*鼠标进入时
*/
function getPathOver(obj){
	$("#pic").toggle(500);
	$("#pic").attr({"src":obj.src});
	
}
/**
*鼠标退出时
*/
function getPathOut(){
	$("#pic").css({"display":"none"});
}
/** 
 * 遍历表格内容返回数组
 * @param Int  id 表格id
 * @return Array
 */
function GetInfoFromTable(tableid) {
	 //定义一个变量
	  var a = 0;
	  var b=0;
	  $("#idTest3").find("tr").each(function(i,item){
			
			a=i
	  })
	  //判断数量是否为空
	  $("input[name='nubText']").each(function(){
		 if( $(this).val().trim() != '0' ) {
			a=parseInt(a)-1;
		  }
	  });
	var aVal=a;
	
	 //定义一个空的变量
	 var result="";
	  var tableObj = document.getElementById(tableid);
	  for (var i = 0; i < tableObj.rows.length; i++) {  //遍历Table的所有Row
	    for (var j = 0; j < tableObj.rows[i].cells.length; j++) {  //遍历Row中的每一列
	      /*alert(tableObj.rows[i].cells[1].innerText);*/
	    	 var a=tableObj.rows[i].cells[3];
	    	 var b=tableObj.rows[i].cells[4];
	    	
	    	 var datatab3=$(a).children().val()//取到数量
	    	 var datatab4=$(b).children().val()//取到小计
	    	
	    	  var datatab2=tableObj.rows[i].cells[1].innerText;//乐器名
	    	  var datatab=tableObj.rows[i].cells[0].innerText;//id
	    	  var datatab6=tableObj.rows[i].cells[2].innerText;//单价
	    
	     
	    }
	    if(i!=0&&aVal==0){
	   		 /* $("#inputss").val($("#inputss").val()+vas+"#");*/
	   		$("#inputss").val($("#inputss").val()+datatab+"#"+datatab2+"#"+datatab6+"#"+datatab3+"#"+datatab4+",");
	   		
	    	
	    }
	    //判断是否选中了采购乐器
	    if(i!=0){
	    	var result="1";
	    }
	    
	  }
	  var str = "";
	  var strs ="";
	  $("input[name='title']").each(function(){
		  if( $(this).val().trim() == '0') { 
			  strs="1";
		  }
		});
	 //判断添加是否成立
	  $("#inputText").val($("#inputText").val()+","+$("#remark").val());
	  if(result==""){
		 
		  if($("#remark").val()==""){
				 layer.msg("请填写备注");
			 }else if(strs=="1"){
				  layer.msg("采购数量不能为0");
			 }else{
				 var url="../../listenPurchase/findFinanceByCompanyId.action";
				 var data=null;
				 $.post(url,data,function(mes){
					 if(mes!=null){
						 if(mes.companyPrice<$("#inputText").val().split(",")[0]){
							 var sucha=$("#inputText").val().split(",")[0]-mes.companyPrice;
							 layer.msg("采购不了，公司财务不够，还差"+sucha);
						 }else{
							 var musicPurchase=$("#inputText").val();
							 var musicPurchaseDetail=$("#inputNum").val();
							 var purId=$("#pursId").val();
							 var url="../../listenPurchase/updateMusicPurchase.action";
							 var data={"musicPurchase":musicPurchase,"musicPurchaseDetail":musicPurchaseDetail,"purId":purId,"updateType":1}
							 $.post(url,data,function(mes){
								 if(mes.datas==1){
									 layer.msg(mes.msg);
									 setTimeout(() => {
										 window.parent.location.reload()
									     var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
									     parent.layer.close(index);//关闭当前页  
										}, 500);
									
								 }
							 },"json")
						 }
					 }
					
				 },"json") 
			 }
		     
	  }else{
		  if($("#inputss").val()!=""  && $("#remark").val()!=""){
			    var sumPrice=0;
			  	$(".inputskx").each(function(){
					 sumPrice+=parseFloat($(this).val());
				})
			  	var sumAllPrice=parseFloat(sumPrice)+parseFloat($("#inputText").val().split(",")[0]);
				var sumNum=0;
			  	$(".inputs-number").each(function(){
					  sumNum+=parseFloat($(this).val());
				})
				var sumAllNum=parseFloat(sumNum)+parseFloat($("#inputText").val().split(",")[1]);
			  	if(strs=="1"){
			  		layer.msg("采购数量不能为0");
			  	}else{
			  		$("#inputText").val(sumAllPrice+","+sumAllNum);
				  	$("#inputText").val($("#inputText").val()+","+$("#remark").val())
				  	var url="../../listenPurchase/findFinanceByCompanyId.action";
				    var data=null;
					 $.post(url,data,function(mes){
							 if(mes!=null){
								 var sunm=$("#inputText").val().split(",")[0];
								 if(mes.companyPrice<sunm){
									 var sucha=sunm-mes.companyPrice;
									 layer.msg("采购不了，公司财务不够，还差"+sucha);
								 }else{
									 var musicPurchase=$("#inputText").val();
									 var musicPurchaseDetail=$("#inputss").val();
									 var purId=$("#pursId").val();
									 var url="../../listenPurchase/updateMusicPurchase.action";
									 var data={"musicPurchase":musicPurchase,"musicPurchaseDetail":musicPurchaseDetail,"purId":purId,"updateType":2}
									 $.post(url,data,function(mes){
										 if(mes.datas==1){
											 layer.msg(mes.msg);
											 setTimeout(() => {
												 window.parent.location.reload()
											     var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
											     parent.layer.close(index);//关闭当前页  
												}, 500);
										 }
									 },"json")
									 
							 }
						  }
					},"json")
			  	}
			 }else{
				 if($("#remark").val()==""){
					 layer.msg("请填写备注");
				 }else{
					 layer.msg("采购数量不能为空");
				 }
				 
			 } 
	  }
	 
	 /*if(a!=0){
		  alert("请填写备注");
	  }else{
		  alert("可以添加");
	  }*/
	}
 
//接收到ajax传过来的对象 
function load() {
	var form = layui.form;
	 form.render();
}
//只能输入数字  兼容火狐
function keypress(_this){
	_this.value = _this.value.replace(/[^0-9]/g, '');
} 
function upperCase(obj){
	
	var stockNumber=$(obj).parent().next().next().html()//取到库存
	var thisVal=$(obj).val();//数量
	var wholesVal=$(obj).parent().prev().html();  //获取单价
	var sd=$(obj).parent().next().children();  //获取小计
	
	var first=thisVal.substr(0,1);
	if(first==0){
		 
		var val=thisVal.replace("0","")
		$(obj).val(val)
	}
	//alert(nextVal);
	if(thisVal==""){
		$(obj).val(0)
	}else{
		if(thisVal<=0){
			$(obj).val(0)
		}else if(parseInt(thisVal)>parseInt(stockNumber)){
			$(obj).val(stockNumber)
		} 
	}

	$(sd).val(parseInt($(obj).val())*parseInt(wholesVal));
 	
	/*$("#idTest3").find("tr").each(function(i,item){
		var sumPriceTd=$(item).find("td").get(3);
		var sumPriceInput=$(sumPriceTd).children().val();
		if(sumPriceInput){
			sumPrice+=parseFloat(sumPriceInput);
		}
	})*/
	
	
}

//接收到ajax传过来的对象 
function load() {
	var form = layui.form;
	 form.render();
}
function updateNum(obj){
	
	
	var thisValP=$(obj).parent();
	var vocationalWorkId=thisValP.parent().next().next().next().children().html();
	var snum=thisValP.parent().next().next().children().children();//取到小计
	var thisVal=$(obj).val();//数量
	var sprice=thisValP.parent().next().children().html();//单价
	
	/*var wholesVal=$(obj).parent().prev().html();  //获取单价
	var sd=$(obj).parent().next().children();  //获取小计
*/	
	var data={"vocationalWorkIds":vocationalWorkId};
	var url="../../listenPurchaseDetail/findByVocationalWorkId.action";
	
	$.post(url,data,function(mes){
		if(thisVal==""){
			$(obj).val(0)
		}else{
			if(thisVal<=0){
				$(obj).val(0)
			}else if(parseInt(thisVal)>parseInt(mes)){
				layer.msg("不能大于总数量")
				$(obj).val(mes)
			} 
		}
	},"json")
	$(snum).val(parseInt($(obj).val())*parseInt(sprice));
		
	var first=thisVal.substr(0,1);
	if(first==0){
		 
		var val=thisVal.replace("0","")
		$(obj).val(val)
	}
	
	layui.use('table',function(){
		var table = layui.table;
		var tables=table.cache.testReload;
		$("#inputNum").val("");
		$.each(tables,function(i,item){
			$("#inputNum").val($("#inputNum").val()+item.pdId+"#"+$("#number"+item.pdId).val()+"#"+$("#price"+item.pdId).val()+",");
		});
	});
	
}
function removeChecked(raId){
 	$('#rawstockType').next().find('.layui-table-body tr').each(function(index,item){
		var ids=$(item).find('td[data-field="muId"]').text();
		console.info(ids);
		if(raId==ids){
			var index=$(item).data('index');
            var che = $('#rawstockType').next().find('.layui-table-body tr[data-index="'+index+'"] input[name="layTableCheckbox"]')
            console.info(che)
            che.prop("checked",false)
           load();
		}
	});

}
